<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/01/30 09:32:42 $)
// $RCSfile: cron_autoclose.php,v $ : $Revision: 1.7 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Prints Debug Output
*/
function autoCloseDebug($str)
{
	if ($_GET["debug"] == 1)
	{
		echo $str;
	}
}

autoCloseDebug("Starting Auto Close<br>");
// Check to see if auto close is enabled
if ($_SWIFT["settings"]["t_enautoclose"] == 1)
{
	autoCloseDebug("Auto Close is enabled<br>");
	// Ok, its enabled.
	$_ticketstatusidlist = $_departmentidlist = array();
	$fautoclose = 0;
	if (_is_array($_SWIFT["settings"]["t_acstatus"]))
	{
		$_ticketstatusidlist = $_SWIFT["settings"]["t_acstatus"];
	}

	if (_is_array($_SWIFT["settings"]["t_acdep"]))
	{
		$_departmentidlist = $_SWIFT["settings"]["t_acdep"];
	}

	autoCloseDebug("Ticket Status List: <br>");
	autoCloseDebug("<br>Department ID List:<br>");

	// Make sure we have the ticket status and departments
	$_changestatus = $_SWIFT["statuscache"][$_SWIFT["settings"]["t_acstatusch"]];
	if (count($_ticketstatusidlist) && count($_departmentidlist) && !empty($_changestatus["ticketstatusid"]) && !empty($_SWIFT["settings"]["t_acinactive"]) && !empty($_SWIFT["settings"]["t_acnoticeclose"]))
	{
		// All Checks done, we are good to go.
		$_inactivetime = DATENOW - ($_SWIFT["settings"]["t_acinactive"]*60*60);
		$_actime = DATENOW + ($_SWIFT["settings"]["t_acnoticeclose"]*60*60);
		$_ticketidlist = $_acticketidlist = $_actickets = $_statuschangelist = $_ticketobjlist = array();

		autoCloseDebug("<Br>Fetching Tickets<br>");

		$dbCore->query("SELECT `ticketid`, `email`, `tgroupid`, `autoclosetimeline` FROM `". TABLE_PREFIX ."tickets` WHERE `departmentid` IN (". buildIN($_departmentidlist) .") AND `ticketstatusid` IN (". buildIN($_ticketstatusidlist) .") AND `lastactivity` <= '". intval($_inactivetime) ."';");
		while ($dbCore->nextRecord())
		{
			// Auto close timeline is empty.. we need to send notice to client..
			if (empty($dbCore->Record["autoclosetimeline"]) && !empty($_SWIFT["settings"]["t_acnoticeclose"]))
			{
				$_actickets[] = $dbCore->Record;
				$_acticketidlist[] = $dbCore->Record["ticketid"];
				autoCloseDebug("Sending Notification<br>");
			} else if (empty($_SWIFT["settings"]["t_acnoticeclose"])) {
				$_actickets[] = $dbCore->Record;
				$_acticketidlist[] = $dbCore->Record["ticketid"];
				// Immediately close without sending notification
				$_statuschangelist[] = $dbCore->Record["ticketid"];
				autoCloseDebug("Changing Status<br>");
			} else if (!empty($dbCore->Record["autoclosetimeline"]) && $dbCore->Record["autoclosetimeline"] < DATENOW && $dbCore->Record["ticketstatusid"] != $_changestatus["ticketstatusid"]) {
				$fautoclose = 1; //Enable Autoclose email.
				$_actickets[] = $dbCore->Record;
				$_acticketidlist[] = $dbCore->Record["ticketid"];
				// We need to change the status
				$_statuschangelist[] = $dbCore->Record["ticketid"];
				autoCloseDebug("Changing Status<br>");
			}
		}

//		print_r($_actickets);
//		print_r($_statuschangelist);

		// ======= SEND NOTICE TO CLIENTS =======
		require_once ("./includes/functions_mail.php");
		$mailObj = new SWIFT_Mail();
		$template->loadLanguageSection("ticketemails", TEMPLATE_DB);

		$index = 0;
		$_ticketobjlist = array();
		foreach ($_actickets as $key=>$val)
		{
			$mailObj = new SWIFT_Mail();
			$_ticketobjlist[$index] =& new TicketMain($val["ticketid"], false, LOG_SYSTEM);
			$_ticketobj = &$_ticketobjlist[$index];

			$_tgroupid = iif(empty($val["tgroupid"]), 1, $val["tgroupid"]);

			// See if tgroupid is set?
			$template->setGroup($_tgroupid);

			$_ticketobj->loadTemplateVariables();
			//Mahesh Slaria: Autoclose elmail
			if ($fautoclose == 1)
			{
			$emailqueueid = $_ticketobj->ticket["emailqueueid"];
			$template->assign("queuesignature", $_SWIFT["queuecache"]["list"][$emailqueueid]["contents"]);
			$template->assign("ishtml", true);
			$_templateresulthtml = $template->displayTemplate("email_autoclose_final", TEMPLATE_DB);
			$template->assign("ishtml", false);
			$_templateresulttext = $template->displayTemplate("email_autoclose_final", TEMPLATE_DB);
			$mailObj->setSubject($_ticketobj->getEmailSubject(SUBJECT_USER));
			$mailObj->setData($_templateresulthtml, $_templateresulttext);
			$returnemail = $_ticketobj->getReturnEmail();
			$returnname = $_ticketobj->getReturnName();
			}else {
			$emailqueueid = $_ticketobj->ticket["emailqueueid"];
			$template->assign("queuesignature", $_SWIFT["queuecache"]["list"][$emailqueueid]["contents"]);
			$template->assign("ishtml", true);
			$_templateresulthtml = $template->displayTemplate("email_autoclose", TEMPLATE_DB);
			$template->assign("ishtml", false);
			$_templateresulttext = $template->displayTemplate("email_autoclose", TEMPLATE_DB);
			$mailObj->setSubject($_ticketobj->getEmailSubject(SUBJECT_USER));
			$mailObj->setData($_templateresulthtml, $_templateresulttext);
			$returnemail = $_ticketobj->getReturnEmail();
			$returnname = $_ticketobj->getReturnName();
			}
			$mailObj->sendMail(array($_ticketobj->ticket["email"]), $returnemail, $returnname, false);

			$index++;
		}

		// ======= UPDATE AUTO CLOSE TIMELINE =======
		if (count($_acticketidlist))
		{
			$dbCore->query("UPDATE `". TABLE_PREFIX ."tickets` SET `autoclosetimeline` = '". intval($_actime) ."' WHERE `ticketid` IN (". buildIN($_acticketidlist) .");");
		}

		// ======= CHANGE STATUS OF TICKETS =======
		$index = 0;
		$_ticketobjlist = array();
		foreach ($_statuschangelist as $key=>$val)
		{
			$_ticketobjlist[$index] =& new TicketMain($val, false, LOG_SYSTEM);
			$_ticketobj = &$_ticketobjlist[$index];

			$_ticketobj->changeStatus($_changestatus["ticketstatusid"], true);
			$index++;
//			echo "Changed Status for Ticket #: ".$_ticketobj->ticket["ticketid"]."<BR />";
		}
	} else {
//		echo "One of the auto close checks failed!<BR />";
	}
} else {
//	echo "Auto Close is Disabled!<BR />";
}
?>